package com.kaifamiao.jdbc.data.dao;

import com.kaifamiao.jdbc.data.entity.Customer;
import com.kaifamiao.jdbc.helper.JdbcHelper;

import java.util.List;

public class CustomerDao implements Dao<Customer,Integer>{

    private static final String SELECT_MAX_ID = "SELECT max(id) FROM t_customers";
    private static final String INSERT = "INSERT INTO t_customers (username, password, salt, nickname, reg_date, id) VALUES (?,?,?,?,?,?)";

    @Override
    public Customer find(Integer integer) throws DaoException {
        return null;
    }

    @Override
    public List<Customer> findAll() throws DaoException {
        return null;
    }

    @Override
    public boolean save(Customer c) throws DaoException {
        JdbcHelper h = JdbcHelper.getInstance();
        // 为即将保存的Customer设置ID
        c.setId( this.nextId() );
        // 调用从 Dao接口 继承的 default方法 将 LocalDate 转换为 java.sql.Date
        java.sql.Date date = toDate( c.getRegistrationDate() );
        Object[] params = {c.getUsername(), c.getPassword(), c.getSalt(), c.getNickname(), date, c.getId()};
        try {
            int count = h.execute(INSERT, params);
            return count == 1;
        } catch ( Exception cause ) {
            throw new DaoException( "用户保存失败" , cause);
        }
    }

    @Override
    public boolean update(Customer customer) throws DaoException {
        return false;
    }

    @Override
    public boolean delete(Integer integer) throws DaoException {
        return false;
    }

    // 获得下一个主键
    private Integer nextId(){
        JdbcHelper h = JdbcHelper.getInstance();
        Integer maxId = h.single(SELECT_MAX_ID, rs -> rs.getInt( 1 ) );
        h.release();
        return maxId == null ? 1 : maxId+1;
    }
}
